package org.alis.rpc.common.serializer.hessian;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import lombok.extern.slf4j.Slf4j;
import org.alis.rpc.common.exception.SerializerException;
import org.alis.rpc.common.serializer.Serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Objects;

/**
 * @author lc
 * @version v1.0.0
 * @date 2020/8/20 17:15
 * @className Hessian1Serializer.class
 */
@Slf4j
public class Hessian1Serializer implements Serializer {

    @Override
    public <T> byte[] serializer(T obj) {
        HessianOutput ho = null;
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()){
            ho = new HessianOutput(os);
            ho.writeObject(obj);
            ho.flush();
            return os.toByteArray();
        } catch (Exception e) {
           throw new SerializerException(e);
        } finally {
            if(Objects.nonNull(ho)){
                try {
                    ho.close();
                } catch (IOException e) {
                    log.error("关闭hessianOutput失败,异常堆栈->",e);
                }
            }
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T deserializer(byte[] bytes, Class<T> clazz) {
        HessianInput hi = null;
        try(ByteArrayInputStream is = new ByteArrayInputStream(bytes)){
            hi = new HessianInput(is);
            return (T)hi.readObject();
        }catch (Exception e){
            throw new SerializerException(e);
        }finally {
            if(Objects.nonNull(hi)){
                hi.close();
            }
        }
    }

}